<template>
  <section
    class="OcePagination"
    :style="{ justifyContent: content || 'center' }"
  >
    <el-pagination
      background
      :layout="defaultPage.layout"
      :total="defaultPage.total"
      :page-size.sync="defaultPage.pageSize"
      :page-sizes="defaultPage.pageSizes"
      :current-page.sync="defaultPage.currentPage"
      :pager-count="defaultPage.pagerCount"
      @size-change="sizeChange"
      @current-change="currentChange"
      v-if="show"
    >
    </el-pagination>
  </section>
</template>

<script>
export default {
  name: 'OcePagination',
  props: {
    // 当前分页对象 包含 页码数和分页数
    page: {
      type: Object,
      default() {
        return {}
      },
    },
    content: {
      type: String,
      default() {
        return 'center'
      },
    },
  },
  data() {
    return {
      show: true,
      defaultPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页码
        pageSize: 10, // 分页数
        pagerCount: 5, // 分页按钮数量
        pageSizes: [10, 20, 30, 40, 50, 100],
        layout: 'total, sizes, prev, pager, next, jumper',
      },
    }
  },
  watch: {
    page: {
      handler() {
        this.pageInit()
      },
      deep: true,
    },
    'defaultPage.currentPage': {
      handler() {
        // console.log(`页码发生变化：${val}`)
        // 为解决标签无法及时刷新
        this.$nextTick(() => {
          this.show = false
          this.$nextTick(() => {
            this.show = true
          })
        })
      },
      deep: true,
    },
  },
  created() {
    this.pageInit()
  },
  methods: {
    pageInit() {
      this.defaultPage = Object.assign(this.defaultPage, this.page, {
        total: Number(
          this.$ocean.vaildData(this.page.total, this.defaultPage.total)
        ),
        pagerCount: Number(this.page.pagerCount || this.defaultPage.pagerCount),
        currentPage: Number(
          this.page.currentPage || this.defaultPage.currentPage
        ),
        pageSize: Number(this.page.pageSize || this.defaultPage.pageSize),
      })
      this.updateValue()
    },
    updateValue() {
      this.$emit('update:page', this.defaultPage)
    },
    // 页码发生变化
    currentChange(val) {
      this.updateValue()
      // console.log(`回调页码：${val}`)
      this.$emit('current-change', val)
    },
    // 页大小回调
    sizeChange(val) {
      this.defaultPage.currentPage = 1
      this.defaultPage.pageSize = val
      this.updateValue()
      this.$emit('size-change', val)
    },
  },
}
</script>

<style lang="scss" scoped>
.OcePagination {
  width: calc(100% - 32px);
  display: flex;
  padding: 16px;
}
</style>
